package com.sgb.kjwl.view.ui.adapter.packers;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import com.sgb.kjwl.R;
import com.swgk.core.base.CallBack;
import com.swgk.core.dialog.ImagesPreviewDialog;
import com.swgk.core.util.GlideEngine;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author: 王彬臣
 * @date: 2021/9/8
 * @Description: 每个工队相册图片Adapter
 */
public class AlbumImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mLayoutInflater;
    private CallBack callBack;
    private Context mContext;
    /**
     * 选择图片后返回的LocalMedia
     **/
    private List<LocalMedia> mData;
    /**
     * 本地文件List
     **/
    private List<File> fileList;
    /**
     * 网络图片和本地图片地址组合在一起的List
     **/
    private ArrayList<String> urls;
    /**
     * 网络图片地址List
     **/
    private List<String> neImgList;
    private Intent intent;
    /**
     * 上传图片的最大张数
     **/
    private int maxSize;
    /**
     * 脚布局
     **/
    private int TYPE_FOOT = 1001;
    /**
     * 是否有弹窗 0：无    1：有
     **/
    private int type;

   public delClickListener delClickListener;
    /**
     * 删除勾选集合
     */
   Map<Integer,String> delMap=new HashMap<>();
    /**
     * 是否显示复选框
     */
   boolean isShowEdit;

   int mainItemPosition;
   public onMainItemClickListener onMainItemClickListener;

    public void setOnMainItemClickListener(AlbumImageAdapter.onMainItemClickListener onMainItemClickListener) {
        this.onMainItemClickListener = onMainItemClickListener;
    }

    public void setShowEdit(boolean showEdit) {
        isShowEdit = showEdit;
    }

    public void setDelClickListener(AlbumImageAdapter.delClickListener delClickListener) {
        this.delClickListener = delClickListener;
    }

    public Map<Integer, String> getDelMap() {
        return delMap;
    }

    public AlbumImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, int mainItemPosition) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        this.mainItemPosition=mainItemPosition;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
    }

    public AlbumImageAdapter(Context context, List<LocalMedia> data, List<String> urls, int maxSize, CallBack callBack) {
        mContext = context;
        mData = new ArrayList<>();
        this.urls = new ArrayList<>();
        this.maxSize = maxSize;
        fileList = new ArrayList<>();
        neImgList = new ArrayList<>();
        mLayoutInflater = LayoutInflater.from(context);
        this.callBack = callBack;
    }



    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOT) {
            View headerView = mLayoutInflater.inflate(R.layout.team_item_device_foot, parent, false);
            return new FootViewHolder(headerView);
        }
        View inflate = mLayoutInflater.inflate(R.layout.item_team_pic, parent, false);
        return new ViewHolder(inflate);

    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            //如果地址包含http，就用网络加载图片的方式
            RequestOptions options = new RequestOptions().placeholder(mContext.getResources().getDrawable(R.drawable.null_img_list));
            Glide.with(mContext).load(urls.get(position)).apply(options).into(((ViewHolder) holder).img);
            //点击图片
            ((ViewHolder) holder).img.setOnClickListener(view -> openPhotoView(position));

            //点击复选按钮
            ((ViewHolder) holder).delView.setOnClickListener(v -> {
                if( ((ViewHolder) holder).delView.isSelected()) {
                    if(delMap.containsKey(position)) {
                        delMap.remove(position);
                    }
                    ((ViewHolder) holder).delView.setSelected(false);
                }else{
                    delMap.put(position,urls.get(position));
                    ((ViewHolder) holder).delView.setSelected(true);
                }
                if(onMainItemClickListener!=null){
                    onMainItemClickListener.getDelMap(mainItemPosition,delMap);
                }

            });
            if(isShowEdit){
                ((ViewHolder) holder).delView.setVisibility(View.VISIBLE);
            }else{
                ((ViewHolder) holder).delView.setVisibility(View.GONE);
            }
        } else if (holder instanceof FootViewHolder) {
            ((FootViewHolder) holder).add_rl.setOnClickListener(v -> {
                if (urls.size() == maxSize) {
                    MToast.showToast(mContext, "最多选择" + maxSize + "张图片");
                } else {
                        openAlbum();
                }
                if(onMainItemClickListener!=null){
                    onMainItemClickListener.onItemClick(mainItemPosition);
                }
            });
            if(isShowEdit){
                ((FootViewHolder) holder).add_rl.setVisibility(View.GONE);
            }else{
                ((FootViewHolder) holder).add_rl.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (maxSize == 1 || urls.size() == 0) {
            return 1;
        } else if(maxSize!=urls.size()){ //加了头布局,多一个
            return urls.size() + 1;
        }else{
            return urls.size();
        }


    }

    @Override
    public int getItemViewType(int position) {
        //在第一个位置添加头
        if (urls.size() != 0) {
            if (urls.size()!=maxSize&&position == urls.size()) {//当添加图片没到达张数，加头布局
                return TYPE_FOOT;
            }
        } else {
            if (position == 0) {
                return TYPE_FOOT;
            }
        }
        return super.getItemViewType(position);
    }

    //设置本地图片
    public void setDatas(List<LocalMedia> mData, List<String> urls) {
        //防止图片重复  可优化
        this.urls.clear();
        this.urls.removeAll(urls);
        if (neImgList.size() != 0) {
            this.urls.addAll(neImgList);
        }/* else {
            this.urls.clear();
        }*/
        this.urls.addAll(urls);
        this.mData = mData;
        notifyDataSetChanged();
    }

    /**
     * 设置图片文件List
     **/
    public void setFileList(List<File> fileList) {
        this.fileList = fileList;
    }

    /**
     * 设置网络图片List
     */
    public void setNetImgList(List<String> netImgList) {
        if (netImgList == null) {
            this.neImgList = new ArrayList<>();
        } else {
            this.neImgList = netImgList;
            this.urls.addAll(netImgList);
        }
        notifyDataSetChanged();
    }

    /**
     * 删除网络图片List
     */
    public void removeNetImgList(List<String> albumList) {
        for (int i = 0; i < neImgList.size(); i++) {
            for (int j = 0; j < urls.size(); j++) {
                if (urls.get(j).equals(neImgList.get(i))) {
                    urls.remove(j);
                }
            }
        }
//        urls.removeAll(neImgList);
        notifyDataSetChanged();
    }

    /**
     * 获取已选择的本地文件List
     **/
    public List<File> getFileList() {
        return this.fileList;
    }

    /**
     * 获取所有的地址List，包括网络和本地
     **/
    public ArrayList<String> getUrls() {
        return urls;
    }

    /**
     * 获取网络图片地址List
     **/
    public List<String> getNetUrls() {
        return neImgList;
    }

    /**
     * 获取已选择的LocalMedia List
     **/
    public List<LocalMedia> getLocalMedia() {
        return mData;
    }

    /**
     * 预览
     * @param position
     */
    private void openPhotoView(int position) {
        if (intent == null) {
            intent = new Intent();
        }
        ImagesPreviewDialog.newInstance(urls, position).show(mContext);
    }

    /**
     * 尾布局的viewholder
     */
    class FootViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout add_rl;

        FootViewHolder(View itemView) {
            super(itemView);
            add_rl = itemView.findViewById(R.id.add_rl);
        }
    }


    /**
     * 正常内容的viewholder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        ImageView img;
        ImageView delView;

        ViewHolder(View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.photo_img);
            delView = itemView.findViewById(R.id.delete_tv);
        }
    }

    public void openAlbum() {
        if (callBack != null) {
            callBack.onFailed(0, 0, "选择图片");
        }
        PictureSelector.create((Activity) mContext)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(maxSize - neImgList.size())//判断还能选多少张图片
                .imageEngine(GlideEngine.createGlideEngine())
                .compress(true)//是否压缩
                .minimumCompressSize(1024*5)//小于5M不压缩
                .selectionMedia(mData)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }
   public interface delClickListener{
        void del(int position);
    }
   public interface onMainItemClickListener{
        void onItemClick(int position);

        void getDelMap(int mainPosition,Map<Integer,String> delMap);
    }
}